<?php
/*
	stmp发送邮件类
*/

set_time_limit(600);
class smtp{
	private $host;          //主机
	private $port;          //端口 一般为25
	private $user;          //SMTP认证的帐号
	private $pass;          //认证密码
	
	private $in;          //客户机发送的命令
	private $out;			//返回命令
	
	private $conn;
	private $socket;
	
	function smtp(){
		$this->host   = SMTP_HOST;
		$this->port   = SMTP_PORT;
		$this->user   = base64_encode(SMTP_USER);
		$this->pass   = base64_encode(SMTP_PASSWORD);
		$this->socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); 
		if(!$this->socket){
			throw new Exception("创建SOCKET:".socket_strerror(socket_last_error()));
		}
		$this->conn = socket_connect($this->socket,$this->host,$this->port);
		if(!$this->conn){
			throw new Exception("建立连接:".socket_strerror(socket_last_error()));
		}
	}
	function send($to,$user_name,$subject,$body){
		$to=trim($to);
		$subject=trim($subject);
		$body=trim($body);
		$user_name=trim($user_name);
		if(!ereg("^[a-zA-Z_][a-zA-Z_0-9\.]*@[a-zA-Z_0-9]+(\.[a-zA-Z_0-9]+)+$",$to) || empty($body)){
			return -1;	//输入参数不正确
		}
		empty($subject) && $sebject = "飞丁网系统邮件";
		empty($user_name) && $user_name = '飞丁网用户';
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		//$headers .= 'Content-Transfer-Encoding: 8bit'."\r\n";
		// Additional headers
		$headers .= 'To: "=?utf-8?B?'.base64_encode($user_name).'?=" <'.$to.'>' . "\r\n";
		$headers .= 'From: "=?utf-8?B?'.base64_encode("飞丁网").'?=" <'.SMTP_USER.'>' . "\r\n";
		$headers .= 'Reply-To: '. SMTP_USER . "\r\n";
		$headers .= 'Subject: =?utf-8?B?'.base64_encode($subject).'?='."\r\n";
		$headers .= 'Date: '.@date('D, j M Y H:i:s O')."\r\n";
		$headers .= 'X-Mailer: SMTPClass of PHP 1.0'."\r\n";
		
		$body = $headers."\r\n".$body;
		
		$this->in       =  "EHLO HELO\r\n";
		$this->docommand();
		$this->in       =  "AUTH LOGIN\r\n";
		$this->docommand();
		$this->in       =  $this->user."\r\n";
		$this->docommand();
		$this->in       =  $this->pass."\r\n";
		$this->docommand();
		$i = 0;
		while(!eregi("235",$this->out)){
			$this->out=socket_read($this->socket,1024);
		   	//认证失败
			if($i++>5){
				return -2;
			}
		}
		$this->in       =  "MAIL FROM:<webservice@fdings.com>\r\n";
		$this->docommand();
		$this->in       =  "RCPT TO:<".$to.">\r\n";
		$this->docommand();
		$this->in       =  "DATA\r\n";
		$this->docommand();
		$this->in       =  $body."\r\n.\r\n";
		$this->docommand();
		if(!eregi("250",$this->out)){
		   return -3;	//发送失败
		}
		$this->in = "QUIT\r\n";
		$this->docommand();
		return 0;
	}
	function docommand(){
		socket_write ($this->socket, $this->in, strlen ($this->in));
		$this->out=socket_read($this->socket,1024);
		//echo 'send:'.$this->in."\n";
		//echo 'recive:'.$this->out."\n";
	}
}